<template>
    <div class="workloadStatistics">
	    <el-form :inline="true" :model="ruleForm" class="demo-form-inline">
	    	<el-radio-group v-model="ruleForm.period" size="small" @change="searchlist">
	    	    <el-radio-button label='d'>今天</el-radio-button>
	    	    <el-radio-button label='db'>昨天</el-radio-button>
	    	    <el-radio-button label='w'>最近7天</el-radio-button>
	    	    <el-radio-button label='m'>最近30天</el-radio-button>
	    	</el-radio-group>
	    	<el-date-picker
	    	        class="ml5"
	    	        size="small"
	    	        v-model="time"
	    	        type="daterange"
	    	        range-separator="至"
	    	        start-placeholder="开始时间"
	    	        end-placeholder="结束时间"
	    	        value-format="yyyy-MM-dd"
	    	        :picker-options="pickerOptions"
	    	>
	    	</el-date-picker>
	    	<el-select v-model="ruleForm.cityId" placeholder="城市" size="small" class="select" @change="cityChangeHandle" filterable>
	    	    <el-option v-for="(item,index) in cityList" :key="index" :label="item.city" :value="item.cityId">
	    	    </el-option>
	    	</el-select>
	    	<el-select v-model="ruleForm.devId" placeholder="楼盘名称" size="small" class="select" filterable>
	    	    <el-option v-for="(item,index) in devList" :key="index" :label="item.devName" :value="item.devId">
	    	    </el-option>
	    	</el-select>
	    	<el-select v-model="ruleForm.tradeType" placeholder="成交类型" size="small" class="select">
	    	    <el-option label="成交类型" :value="undefined"></el-option>
	    	    <el-option label="网络推客成交" value="0"></el-option>
	    	    <el-option label="置业专家成交" value="2"></el-option>
	    	    <el-option label="渠道成交" value="1"></el-option>
	    	</el-select>

	    	<el-select v-model="ruleForm.companyId" placeholder="经纪公司" size="small" class="select" filterable :disabled="ruleForm.tradeType!=1">
	    	    <el-option v-for="item in companyList" :key="item.id" :label="item.companyName" :value="item.id"></el-option>
	    	</el-select>
	    	<el-button type="primary" @click="searchlist" size="small" id="monitorEnter">查询</el-button>
	    	<el-button @click="resethander" size="small">重置</el-button>
	    </el-form>

		<div class="tablewrapper">
			<table border="" cellspacing="0" cellpadding="0">
				<tr>
					<th>统计指标</th>
					<th>报备</th>
					<th>带看</th>
					<th>认筹</th>
					<th>认筹金额（元)</th>
					<th>退款金额（元)</th>
					<th>认购</th>
					<th>草签</th>
					<th>签约</th>
					<th>成交金额（元)</th>
				</tr>
				<tr>
					<th>总数</th>
					<td>{{avginfo.report}}</td>
					<td>{{avginfo.look}}</td>
					<td>{{avginfo.raise}}</td>
					<td>{{avginfo.raiseFund}}</td>
					<td>{{avginfo.raiseReFund}}</td>
					<td>{{avginfo.purchase}}</td>
					<td>{{avginfo.initial}}</td>
					<td>{{avginfo.sign}}</td>
					<td>{{avginfo.clinchFund}}</td>
				</tr>
				<tr>
					<th>平均每日</th>
					<td>{{totalInfo.report}}</td>
					<td>{{totalInfo.look}}</td>
					<td>{{totalInfo.raise}}</td>
					<td>{{totalInfo.raiseFund}}</td>
					<td>{{totalInfo.raiseReFund}}</td>
					<td>{{totalInfo.purchase}}</td>
					<td>{{totalInfo.initial}}</td>
					<td>{{totalInfo.sign}}</td>
					<td>{{totalInfo.clinchFund}}</td>
				</tr>
			</table>
		</div>

		<!-- 折线图 -->
        <div id="myChart" style='width: 100%; height:400px;margin-top: 50px;'></div>

        <h3>TOP10排行榜</h3>
        <el-table :data="top10Data" border class="table1">
            <el-table-column type="index" width="100" label="TOP榜单" align="center"></el-table-column>
            <el-table-column prop="report" label="报备"></el-table-column>
            <el-table-column prop="look" label="带看"></el-table-column>
            <el-table-column prop="raise" label="认筹"></el-table-column>
            <el-table-column prop="raiseFund" label="认筹金额"></el-table-column>
            <el-table-column prop="raiseReFund" label="退款金额"></el-table-column>
            <el-table-column prop="purchase" label="认购"></el-table-column>
            <el-table-column prop="initial" label="草签"></el-table-column>
            <el-table-column prop="sign" label="签约"></el-table-column>
            <el-table-column prop="clinchFund" label="成交金额"></el-table-column>
        </el-table>

		<div class="dailyData">
	        <h3>日报数据</h3>
	     	<el-button size="small"  type="primary" @click="exportHandle">导出</el-button>
  		</div>
  		<el-table :data="dailyDataCurrent" border class="table1">
  		    <el-table-column prop="date" label="时间"></el-table-column>
  		    <el-table-column prop="report" label="报备"></el-table-column>
  		    <el-table-column prop="look" label="带看"></el-table-column>
  		    <el-table-column prop="raise" label="认筹"></el-table-column>
  		    <el-table-column prop="raiseFund" label="认筹金额（元）"></el-table-column>
  		    <el-table-column prop="raiseReFund" label="退款金额（元）"></el-table-column>
  		    <el-table-column prop="purchase" label="认购"></el-table-column>
  		    <el-table-column prop="initial" label="草签"></el-table-column>
  		    <el-table-column prop="sign" label="签约"></el-table-column>
  		    <el-table-column prop="clinchFund" label="成交金额（元）"></el-table-column>
  		</el-table>
  		<el-pagination
  		        class="mt10"
  		        background
  		        layout="total, sizes, prev, pager, next"
  		        :current-page.sync="ruleForm.pageNum"
  		        :page-sizes="[10, 20, 30, 40]"
  		        :page-size="ruleForm.pageSize"
  		        @size-change="handleSizeChange"
  		        @current-change="handleCurrentChange"
  		        :total="totalSize">
  		</el-pagination>
    </div>
</template>

<script>
import api from "@/api/apiPath"
import utils from "@/common/utils.js";

// 引入 ECharts 主模块
let echarts = require('echarts/lib/echarts');
// 引入折线图
import 'echarts/lib/chart/line'
// 引入提示框和title组件，图例
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/title'
import 'echarts/lib/component/legend'
import 'echarts/lib/component/legendScroll'//图例滚动
//  //vue全局注入echarts
// Vue.prototype.$echarts = echarts

export default {
    name:"workloadStatistics",
    title:'工作量统计',
    data() {
        return {
        	myChart:undefined,
        	cityList:[],
        	devList:[],
        	companyList:[],
        	tableData:[],
        	top10Data:[],//top10数据
        	dailyDataCurrent:[],//日报数据
        	time:[],
        	ruleForm:{
        		period:'w',//"d","当天","db","昨天","w","当周","m","当月","s","当季度", "y","当年","o","自定义时间"
        		start: "",//开始时间
        		end: "",//结束时间
        		cityId:'',//城市id
        		devId:'',//楼盘id
        		tradeType:'',//	0-网络推客，1- 渠道成交，2-置业专家
        		companyId:'',//公司id
        		pageNum:1,
        		pageSize:10,
        	},
        	totalSize:0,
			avginfo:{},//平均
			totalInfo:{},//总数
        	pickerOptions: {
        	    disabledDate(time) {
        	        return time.getTime() > Date.now()
        	    }
        	},
        }
    },
    activated(){
	  this.searchlist()
    },
    mounted() {
    	this.loadCity()//城市
    	this.allestate()//全部楼盘
    	this.getcompany()//获取经纪公司data
    	this.getecharts() //折线图
    	this.getlist()//获取页面数据
    },
    methods: {
    	getcompany(){
			this.$axios.post('/cms/sys/selectCompany',{}).then(res=>{
				this.companyList = res
			})
    	},
    	resethander(){
    		this.ruleForm = {}
    		this.time = ['','']
    	},
    	handleCurrentChange(){
    		this.dailyDataCurrent = this.dailyData.slice((this.ruleForm.pageNum - 1) * this.ruleForm.pageSize, this.ruleForm.pageNum * this.ruleForm.pageSize)
    	},
    	handleSizeChange(val){
    		this.pageSize = val
    		this.dailyDataCurrent = this.dailyData.slice((this.ruleForm.pageNum - 1) * this.ruleForm.pageSize, this.ruleForm.pageNum * this.ruleForm.pageSize)
    	},
    	cityChangeHandle(){
    		this.ruleForm.devId = ''
    		this.allestate()
    	},
		allestate(){
			this.axios.post(api.ALLESTATEDEVS,{cityId:this.ruleForm.cityId}).then(res=>{
				if (res.data.code == 200) {
					this.devList = res.data.data
					this.devList.unshift({devName:'楼盘名称',devId:''})
				}
			})
		},
    	loadCity(){
    		this.axios.post(api.CITYLIST).then(res => {
    			if (res.data.code !== 200) {
    				this.$message(res.data.msg)
    			}else {
    				this.cityList = res.data.data.cityList
    				this.cityList.unshift({city:'城市',cityId:''})
    			}
    		})
    	},
    	searchlist(){
    		this.ruleForm.pageNum = 1
    		this.getlist()
    	},
		getecharts(){
			// this.myChart = this.$echarts.init(document.getElementById('myChart'));
			this.myChart = echarts.init(document.getElementById('myChart'));
			// 绘制图表
			this.myChart.setOption({
			    title: {
			        text: '趋势图'
			    },
			    tooltip: {
			        trigger: 'axis'
			    },
			    legend: {
			        data:['报备','带看','认筹','认购','草签','签约']
			    },
			    grid: {
			        left: '2%',
			        right: '2%',
			        bottom: '3%',
			        containLabel: true
			    },
			    toolbox: {
			        feature: {
			            saveAsImage: {}
			        }
			    },
			    xAxis: {
			        type: 'category',
			        boundaryGap: false,
			        data:[]
			    },
			    yAxis: {
			        type: 'value'
			    },
			    series: [   
			    ]
			});
		},
    	getlist(){
    		this.ruleForm.start = this.time[0] ? utils.getTimeString(this.time[0]) : ""
    		this.ruleForm.end = this.time[1] ? utils.getTimeString(this.time[1]) : ""
			this.$axios.post('/estate/statistics/jobSummary',this.ruleForm).then(res=>{
				this.avginfo = res.avgInfo
				this.totalInfo = res.totalInfo
				let temp = res
				// 折线图数据
				this.myChart.setOption({
				    xAxis: {type: 'category',  boundaryGap: false, data: temp.x},
				    series: [
				        {name:'报备', type:'line', stack: '总量', data:temp.report.y},
				        {name:'带看', type:'line', stack: '总量', data: temp.look.y},
				        {name:'认筹', type:'line', stack: '总量', data:temp.raise.y},
				        {name:'认购', type:'line', stack: '总量', data:temp.purchase.y},
				        {name:'草签', type:'line', stack: '总量', data:temp.initial.y},
				        {name:'签约', type:'line', stack: '总量', data:temp.sign.y}
				    ]
				});
				//top数据
				var top10 = []
				// 选了楼盘top10只有1条
				if (this.ruleForm.devId) {
				    top10.push({
				        clinchFund: temp.top10.clinchFund && temp.top10.clinchFund[0] ? temp.top10.clinchFund[0] : '',
				        raiseReFund: temp.top10.raiseReFund && temp.top10.raiseReFund[0] ? temp.top10.raiseReFund[0] : '',
				        initial: temp.top10.initial && temp.top10.initial[0] ? temp.top10.initial[0] : '',
				        raiseFund: temp.top10.raiseFund && temp.top10.raiseFund[0] ? temp.top10.raiseFund[0] : '',
				        report: temp.top10.report && temp.top10.report[0] ? temp.top10.report[0] : '',
				        raise: temp.top10.raise && temp.top10.raise[0] ? temp.top10.raise[0] : '',
				        purchase: temp.top10.purchase && temp.top10.purchase[0] ? temp.top10.purchase[0] : '',
				        sign: temp.top10.sign && temp.top10.sign[0] ? temp.top10.sign[0] : '',
				        look: temp.top10.look && temp.top10.look[0] ? temp.top10.look[0] : '',
				    })
				} else {
				    // 求top10的最大行数
				    var arr = [], max = 0
				    temp.top10.clinchFund && arr.push(temp.top10.clinchFund.length)
				    temp.top10.raiseReFund && arr.push(temp.top10.raiseReFund.length)
				    temp.top10.initial && arr.push(temp.top10.initial.length)
				    temp.top10.raiseFund && arr.push(temp.top10.raiseFund.length)
				    temp.top10.report && arr.push(temp.top10.report.length)
				    temp.top10.raise && arr.push(temp.top10.raise.length)
				    temp.top10.purchase && arr.push(temp.top10.purchase.length)
				    temp.top10.sign && arr.push(temp.top10.sign.length)
				    temp.top10.look && arr.push(temp.top10.look.length)
				    for (var aa = 0; aa < arr.length; aa ++) {
				        if (arr[aa] > max) {
				            max = arr[aa]
				        }
				    }
				    for(var j=0; j< max; j++) {
				        top10.push({
				            clinchFund: temp.top10.clinchFund && temp.top10.clinchFund[j] ? temp.top10.clinchFund[j] : '',
				            raiseReFund: temp.top10.raiseReFund && temp.top10.raiseReFund[j] ? temp.top10.raiseReFund[j] : '',
				            initial: temp.top10.initial && temp.top10.initial[j] ? temp.top10.initial[j] : '',
				            raiseFund: temp.top10.raiseFund && temp.top10.raiseFund[j] ? temp.top10.raiseFund[j] : '',
				            report: temp.top10.report && temp.top10.report[j] ? temp.top10.report[j] : '',
				            raise: temp.top10.raise && temp.top10.raise[j] ? temp.top10.raise[j] : '',
				            purchase: temp.top10.purchase && temp.top10.purchase[j] ? temp.top10.purchase[j] : '',
				            sign: temp.top10.sign && temp.top10.sign[j] ? temp.top10.sign[j] : '',
				            look: temp.top10.look && temp.top10.look[j] ? temp.top10.look[j] : '',
				        })
				    }
				}
				//日报数据
				var dailyData = []
				if (temp.x && temp.x.length > 0) {
				    temp.x.forEach((item,k) => {
				        dailyData.push({
				            date: item,
				            clinchFund: temp.clinchFund.y && temp.clinchFund.y.length > 0 ? temp.clinchFund.y[k] : '',
				            raiseReFund: temp.raiseReFund.y && temp.raiseReFund.y.length > 0 ? temp.raiseReFund.y[k] : '',
				            initial: temp.initial.y && temp.initial.y.length > 0 ? temp.initial.y[k] : '',
				            raiseFund: temp.raiseFund.y && temp.raiseFund.y.length > 0 ? temp.raiseFund.y[k] : '',
				            report: temp.report.y && temp.report.y.length > 0 ? temp.report.y[k] : '',
				            raise: temp.raise.y && temp.raise.y.length > 0 ? temp.raise.y[k] : '',
				            purchase: temp.purchase.y && temp.purchase.y.length > 0 ? temp.purchase.y[k] : '',
				            sign: temp.sign.y && temp.sign.y.length > 0 ? temp.sign.y[k] : '',
				            look: temp.look.y && temp.look.y.length > 0 ? temp.look.y[k] : '',
				        })
				    })
				}

				this.top10Data = top10
				this.dailyData = dailyData
				this.totalSize = dailyData.length
				if (this.dailyData.length > this.ruleForm.pageSize) {
				    this.dailyDataCurrent = dailyData.slice(0, this.ruleForm.pageSize)
				} else {
				    this.dailyDataCurrent = dailyData
				}

			})
    	},
    	exportHandle(){
			this.$axios.service({
			  method: "post",
			  url: '/estate/statistics/dataExport',
			  data: this.ruleForm,
			  headers: {
			    "content-type": "application/json; charset=utf-8",
			    token: sessionStorage.getItem("cmsUser")
			      ? JSON.parse(sessionStorage.getItem("cmsUser")).tokenId
			      : ""
			  },
			  responseType: "blob"
			})
			.then(res => {
				this.downloadFile(res.data)
			})
			.catch(res => {
				this.downloadFile(res.data)
			});
    	},
    	// 导出
    	downloadFile(data) {
    	    let url = window.URL.createObjectURL(new Blob([data]));
    	    let link = document.createElement("a");
    	    let fileName = `导出${utils.getTimeString(new Date())}.xls`;
    	    link.style.display = "none";
    	    link.href = url;
    	    link.setAttribute("download", fileName);
    	    document.body.appendChild(link);
    	    link.click();
    	    URL.revokeObjectURL(link.href);
    	    document.body.removeChild(link);
    	    this.$message({
    	      message: "导出成功",
    	      type: "success"
    	    });
    	},

    }
}
</script>
<style lang="stylus" scoped>
	.workloadStatistics {
		.dailyData{
			display: flex;
			justify-content:space-between;
			align-items:center;
		}
		.tablewrapper {
			margin-top: 20px;
			table {
				border:1px solid #EBEEF5;
				border-collapse: collapse;
				font-size: 14px;
				color: #909399;
				th {
					width: 10vw;
					line-height: 40px
					font-weight: 500;
					text-align: left;
					padding-left: 10px;
				}
				td {
					text-align: left;
				    padding-left: 10px;
				}
				
			}
		}
	}




</style>